//
//  BETelephonyNetworkInfo.swift
//  BasicExtensions
//
//  Created by JY_NEW on 2022/3/9.
//

#if canImport(CoreTelephony)

import CoreTelephony

extension CTTelephonyNetworkInfo {
    /// 移动网络第几代，如4G返回4，5G返回5
    public var wwanGeneration: Int? {
        let accessString = self.currentRadioAccessTechnology
        switch accessString {
        case CTRadioAccessTechnologyEdge,
            CTRadioAccessTechnologyGPRS,
        CTRadioAccessTechnologyCDMA1x:
            return 2
        case CTRadioAccessTechnologyHSDPA,
            CTRadioAccessTechnologyWCDMA,
            CTRadioAccessTechnologyHSUPA,
            CTRadioAccessTechnologyCDMAEVDORev0,
            CTRadioAccessTechnologyCDMAEVDORevA,
            CTRadioAccessTechnologyCDMAEVDORevB,
        CTRadioAccessTechnologyeHRPD:
            return 3
        case CTRadioAccessTechnologyLTE:
            return 4
        default:
            if #available(iOS 14.1, *) {
                if accessString == CTRadioAccessTechnologyNRNSA || accessString == CTRadioAccessTechnologyNR {
                    return 5
                }
            }
            return nil
        }
    }
    /// 移动网络运营商
    public var wwanOperator: String? {
        return self.subscriberCellularProvider?.carrierName
    }
    /// IP地址
    public var ipAddress: String {
        var addresses = [String]()
        var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
        if getifaddrs(&ifaddr) == 0 {
            var ptr = ifaddr
            while (ptr != nil) {
                let flags = Int32(ptr!.pointee.ifa_flags)
                var addr = ptr!.pointee.ifa_addr.pointee
                if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                    if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
                        var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                        if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                            if let address = String(validatingUTF8:hostname) {
                                addresses.append(address)
                            }
                        }
                    }
                }
                ptr = ptr!.pointee.ifa_next
            }
            freeifaddrs(ifaddr)
        }
        return addresses.first ?? "0.0.0.0"
    }
}

#endif
